import {app, BrowserWindow, screen} from 'electron';
import * as path from 'path';
import {log} from './logger';
import {listen} from './http-listener';

console.log('electron starting', __dirname);

let win: BrowserWindow | null = null;
const args = process.argv.slice(1);
const serve = args.some(val => val === '--serve');

function createWindow(): BrowserWindow {
  const electronScreen = screen;
  const size = electronScreen.getPrimaryDisplay().workAreaSize;
  win = new BrowserWindow({
    x: 0,
    y: 0,
    // width: size.width,
    // height: size.height,
    width: 1024,
    height: 768,
    webPreferences: {
      nodeIntegration: true,
      allowRunningInsecureContent: serve
    }
  });

  if (serve) {
    // require('devtron').install();
    // win.webContents.openDevTools();

    require('electron-reload')(__dirname, {
      electron: require(path.resolve(__dirname, '../node_modules/electron'))
    });
    win.loadURL('http://localhost:4200');
  } else {
    win.loadURL(`file://${__dirname}/ui/index.html`);
  }

  win.on('closed', () => {
    win = null;
  });
  listen(win);
  return win;
}

try {
  app.allowRendererProcessReuse = true;
  app.on('ready', () => setTimeout(createWindow, 400));
  app.on('window-all-closed', () => {
    log.info('window-all-closed');
    // app.exit();
    if (process.platform !== 'darwin') {
      app.quit();
    }
  });
  app.on('activate', () => {
    if (win === null) {
      createWindow();
    }
  });
} catch (e) {
}
